package model

import (
	"context"
	"time"

	"code.bydev.io/cht/customer/kyc_admin_service/internal/utils"
	"code.bydev.io/frameworks/byone/core/trace"
	"emperror.dev/errors"
	"go.opentelemetry.io/otel"
	"gorm.io/gorm"
)

// KycRecordCommon kyc认证记录
type KycRecordCommon struct {
	ID            uint64    `gorm:"autoIncrement:true;primaryKey;column:id;type:bigint unsigned;not null;comment:'主键id'"`                                        // 主键id
	MemberID      int64     `gorm:"unique;column:member_id;type:bigint;not null;comment:'用户id'"`                                                                 // 用户id
	ApplicantID   string    `gorm:"column:applicant_id;type:varchar(64);not null;default:'';comment:'sumsub applicant_id jumio account_id'"`                     // sumsub applicant_id jumio account_id
	DataID        string    `gorm:"column:data_id;type:varchar(64);not null;default:'';comment:'jumio workflow_execution_id scanReference'"`                     // jumio workflow_execution_id scanReference
	Provider      int8      `gorm:"column:provider;type:tinyint;not null;default:0;comment:'KYC服务提供方,1:sumsub 2:jumio'"`                                         // KYC服务提供方,1:sumsub 2:jumio
	Country       string    `gorm:"column:country;type:varchar(8);not null;default:'';comment:'用户所在国家编码'"`                                                       // 用户所在国家编码
	Level         int8      `gorm:"column:level;type:tinyint;not null;default:0;comment:'KYC等级(0-3)'"`                                                           // KYC等级(0-3)
	LevelName     string    `gorm:"column:level_name;type:varchar(20);not null;default:0;comment:'KYC等级配置'"`                                                     // KYC等级配置
	Type          int8      `gorm:"column:type;type:tinyint;not null;default:0;comment:'KYC类型，0:个人，1:公司'"`                                                       // KYC类型，0:个人，1:公司
	State         int8      `gorm:"index:idx_state;column:state;type:tinyint;not null;default:0;comment:'KYC认证状态,0:init(default),1:pending,2:complete,3:reset'"` // KYC认证状态,0:init(default),1:pending,2:complete,3:reset
	Result        int8      `gorm:"index:idx_result;column:result;type:tinyint;not null;default:0;comment:'KYC认证结果,0:unknown, 1:success, 2:rejected'"`           // KYC认证结果,0:unknown, 1:success, 2:rejected
	RejectLabels  string    `gorm:"column:reject_labels;type:varchar(1024);not null;default:'';comment:'拒绝原因,逗号分割的字符串'"`                                         // 拒绝原因,逗号分割的字符串
	CanReprocess  int8      `gorm:"column:can_reprocess;type:tinyint;not null;default:0;comment:'是否可以重做该等级kyc，-1:不能重试 0: 可重试'"`                                  // 是否可以重做该等级kyc，-1:不能重试 0: 可重试
	CreatedAt     time.Time `gorm:"index:idx_created;column:created_at;type:datetime;not null;default:CURRENT_TIMESTAMP;comment:'创建时间'"`                         // 创建时间
	UpdatedAt     time.Time `gorm:"column:updated_at;type:datetime;not null;default:CURRENT_TIMESTAMP;comment:'物理更新时间'"`                                         // 物理更新时间
	Residence     string    `gorm:"column:residence;type:varchar(10);not null;default:'';comment:'居住地'"`                                                         // 居住地
	Nationality   string    `gorm:"column:nationality;type:varchar(20);not null;default:'';comment:'国籍'"`                                                        // 国籍
	Passed        int8      `gorm:"column:passed;type:tinyint;not null;default:0;comment:'1:通过，2:拒绝'"`                                                           // 1:通过，2:拒绝
	SelectDocType int32     `gorm:"column:select_doc_type;type:tinyint(4);not null;comment:用户选择类型(0:Unspecified;1:ID Card;2:Passport;3:Driver License;4:Residence Permit;5:Bill;33:BVN)" json:"select_doc_type"`
}

func (KycRecordCommon) TableName() string {
	return "kyc_record_common"
}

// GetByMemberID 根据memberID获取记录
func (t *KycRecordCommon) GetByMemberID(ctx context.Context, memberID int64) (*KycRecordCommon, error) {
	ctx, span := otel.Tracer(trace.TracerName).Start(ctx, utils.GetPFuncName())
	defer span.End()

	db := DBBKycNew(ctx)
	record := &KycRecordCommon{}
	if err := db.Take(record, "member_id = ?", memberID).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, nil
		}
		return nil, err
	}
	return record, nil
}

// GetKYCApprovedListByStartID 根据startID获取记录
func (t *KycRecordCommon) GetKYCApprovedListByStartID(ctx context.Context, startID int64, limit int) ([]*KycRecordCommon, error) {
	ctx, span := otel.Tracer(trace.TracerName).Start(ctx, utils.GetPFuncName())
	defer span.End()

	db := DBBKycNew(ctx)
	ret := make([]*KycRecordCommon, 0)
	err := db.Model(KycRecordCommon{}).
		Where("id > ?", startID).
		Where(
			db.Where("level = ? and result = ?", 1, 1).
				Or("level = ?", 2)).
		Order("id asc").
		Limit(limit).
		Find(&ret).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return ret, nil
		}
		return nil, err
	}

	return ret, err
}
